package uk.ac.sanger.das.dasregistry.springrest.coordinates;

import java.util.Date;

import org.apache.log4j.Logger;
import org.biodas.jdas.exceptions.ValidationException;
import org.biodas.jdas.schema.registrycoordinates.DASCOORDINATESYSTEM;
import org.biodas.jdas.schema.sources.COORDINATES;
import org.biodas.jdas.validation.CoordinatesValidator;


public class CoordinatesManagerImpl implements CoordinatesManager {

    Logger logger = Logger.getLogger(CoordinatesManagerImpl.class);
    private CoordinatesDao coordinatesDao;
    long pause = 600000;//refresh all the cache every 10 minutes
    private CoordinatesCache coordinatesCache;
    private final CoordinatesValidator validator = new CoordinatesValidator();

    public CoordinatesManagerImpl() {
    }

    public CoordinatesManagerImpl(CoordinatesDao coordinatesDao) {
        this.coordinatesDao = coordinatesDao;
        coordinatesCache = new CoordinatesCache(coordinatesDao);
        coordinatesCache.start();//start polling the lastupdate and get new coords behind the scenes when there is a change
    }

    public DASCOORDINATESYSTEM getAllCoordinates() {

        return coordinatesCache.getAllCoordinates();
    }

    @Override
    public DASCOORDINATESYSTEM add(DASCOORDINATESYSTEM coordinate) throws DasCoordinateNotRegisterableExcepton {
        if (coordinate.getCOORDINATES().size() == 0 || coordinate.getCOORDINATES().size() > 1) {
            throw new DasCoordinateNotRegisterableExcepton("we only accept posts for one coordinate at the moment");
        }
        COORDINATES coord = coordinate.getCOORDINATES().get(0);
        logger.debug("invalid in dassourcemanager " + coord.getUri());
        // validate the source as it's been requested if not conform then don't
        // add
//		if (!isValid(coord, validator)) {
//			throw new DasCoordinateNotRegisterableExcepton(validator.getMessage());
//		}
        //does this source already exist
        String regId = null;
        try {
            regId = validator.getRegistryId(coord, this.getAllCoordinates().getCOORDINATES());
        } catch (ValidationException e) {
            //  Auto-generated catch block
            e.printStackTrace();
        }
        if (!"".equals(regId)) {
            throw new DasCoordinateNotRegisterableExcepton("source exists already " + regId);
        }

        logger.debug("returning created sources");

        DASCOORDINATESYSTEM addedCoords = null;
        addedCoords = coordinatesDao.add(coord);
        coordinatesCache.add(addedCoords);
        return addedCoords;
    }
//    private boolean isValid(COORDINATES coord, CoordinatesValidator validator) {
//        throw new UnsupportedOperationException("Not yet implemented");
//    }
}
